package com.aliyun.tiangong.support;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.collect.Maps;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import java.util.Map;
import java.util.Objects;

/**
 * @author xinghen
 * @ClassName: RestResult
 * @Package: com.aliyun.tiangong.support
 * @Description rest result
 * @create 2018-04-20 10:18
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RestResult<T> {

    /**
     * 返回成功状态码
     */
    public static final Integer SUCCESS_STATUS = HttpStatus.OK.value();

    /**
     * 返回成功消息
     */
    public static final String SUCCESS_MESSAGE = "操作成功";

    /**
     * 返回失败状态码
     */
    public static final Integer ERROR_STATUS = HttpStatus.INTERNAL_SERVER_ERROR.value();

    /**
     * 返回失败消息
     */
    public static final String ERROR_MESSAGE = "操作失败";

    /**
     * 状态
     */
    private Integer status;

    /**
     * 消息
     */
    private String message;

    /**
     * 数据
     */
    private T data;

    public RestResult() {
    }

    public RestResult(Integer status, String message, T data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    public static <T> RestResult<T> ok(String message, T data) {
        return new RestResult<>(SUCCESS_STATUS, message, data);
    }

    public static <T> RestResult<T> ok() {
        return ok(SUCCESS_MESSAGE, null);
    }

    public static <T> RestResult<T> ok(String message) {
        return ok(message, null);
    }

    public static <T> RestResult<T> ok(T data) {
        return ok(SUCCESS_MESSAGE, data);
    }

    public static <T> RestResult<T> error(Integer status, String message) {
        return new RestResult<>(status, StringUtils.isNotBlank(message) ? message : ERROR_MESSAGE, null);
    }

    public static <T> RestResult<T> error(String message) {
        return error(ERROR_STATUS, message);
    }

    public static <T> RestResult<T> error() {
        return error(ERROR_MESSAGE);
    }

    /**
     * 转换为Map
     *
     * @return
     */
    public Map<String, Object> toMap() {
        Map<String, Object> map = Maps.newHashMap();
        if (Objects.nonNull(this.getStatus())) {
            map.put("status", this.getStatus());
        }
        if (StringUtils.isNotBlank(this.getMessage())) {
            map.put("message", this.getMessage());
        }
        if (Objects.nonNull(this.getData())) {
            map.put("data", this.getData());
        }
        return map;
    }

}
